package com.fm.lockhart.servlet;

import com.fm.base.json.JsonStructure;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public abstract class JsonHttpServlet extends HttpServlet {
	protected abstract JsonStructure get(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
	protected abstract JsonStructure post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;

	private void doReturn(HttpServletResponse resp, JsonStructure json) throws IOException {
		resp.setContentType("application/json;charset=utf-8");
		ServletOutputStream out = resp.getOutputStream();
		out.print(json.toLiteJson());
		out.flush();
		out.close();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JsonStructure json = get(req, resp);
		doReturn(resp, json);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JsonStructure json = post(req, resp);
		doReturn(resp, json);
	}
}
